import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import type { AppConfig, ConnectionConfig } from '../types/config';
import type { SshConnection, Terminal, Tunnel } from '../types/ssh';

interface AppState {
  // 应用配置
  config: AppConfig | null;
  setConfig: (config: AppConfig) => void;
  updateConfig: (updates: Partial<AppConfig>) => void;

  // 连接管理
  connections: ConnectionConfig[];
  setConnections: (connections: ConnectionConfig[]) => void;
  addConnection: (connection: ConnectionConfig) => void;
  updateConnection: (id: string, updates: Partial<ConnectionConfig>) => void;
  removeConnection: (id: string) => void;
  getConnection: (id: string) => ConnectionConfig | undefined;

  // 活动连接
  activeConnections: SshConnection[];
  setActiveConnections: (connections: SshConnection[]) => void;
  addActiveConnection: (connection: SshConnection) => void;
  updateActiveConnection: (id: string, updates: Partial<SshConnection>) => void;
  removeActiveConnection: (id: string) => void;
  getActiveConnection: (id: string) => SshConnection | undefined;

  // 终端管理
  terminals: Terminal[];
  setTerminals: (terminals: Terminal[]) => void;
  addTerminal: (terminal: Terminal) => void;
  updateTerminal: (id: string, updates: Partial<Terminal>) => void;
  removeTerminal: (id: string) => void;
  getTerminal: (id: string) => Terminal | undefined;
  getTerminalsByConnection: (connectionId: string) => Terminal[];

  // 隧道管理
  tunnels: Tunnel[];
  setTunnels: (tunnels: Tunnel[]) => void;
  addTunnel: (tunnel: Tunnel) => void;
  updateTunnel: (id: string, updates: Partial<Tunnel>) => void;
  removeTunnel: (id: string) => void;
  getTunnel: (id: string) => Tunnel | undefined;
  getTunnelsByConnection: (connectionId: string) => Tunnel[];

  // UI状态
  selectedConnectionId: string | null;
  setSelectedConnectionId: (id: string | null) => void;
  selectedTerminalId: string | null;
  setSelectedTerminalId: (id: string | null) => void;
  sidebarOpen: boolean;
  setSidebarOpen: (open: boolean) => void;
  currentPage: string;
  setCurrentPage: (page: string) => void;

  // 搜索和过滤
  searchQuery: string;
  setSearchQuery: (query: string) => void;
  connectionFilter: 'all' | 'connected' | 'disconnected';
  setConnectionFilter: (filter: 'all' | 'connected' | 'disconnected') => void;

  // 通知和错误
  notifications: Array<{
    id: string;
    type: 'info' | 'success' | 'warning' | 'error';
    message: string;
    timestamp: string;
    read: boolean;
  }>;
  addNotification: (notification: Omit<AppState['notifications'][0], 'id' | 'timestamp' | 'read'>) => void;
  markNotificationRead: (id: string) => void;
  clearNotifications: () => void;

  // 应用状态
  isLoading: boolean;
  setIsLoading: (loading: boolean) => void;
  error: string | null;
  setError: (error: string | null) => void;
}

export const useAppStore = create<AppState>()(
  devtools(
    persist(
      (set, get) => ({
        // 应用配置
        config: null,
        setConfig: (config) => set({ config }),
        updateConfig: (updates) => {
          const currentConfig = get().config;
          if (currentConfig) {
            set({ config: { ...currentConfig, ...updates } });
          }
        },

        // 连接管理
        connections: [],
        setConnections: (connections) => set({ connections }),
        addConnection: (connection) => {
          const connections = get().connections;
          set({ connections: [...connections, connection] });
        },
        updateConnection: (id, updates) => {
          const connections = get().connections;
          const index = connections.findIndex(c => c.id === id);
          if (index !== -1) {
            const updatedConnections = [...connections];
            updatedConnections[index] = { ...updatedConnections[index], ...updates };
            set({ connections: updatedConnections });
          }
        },
        removeConnection: (id) => {
          const connections = get().connections;
          set({ connections: connections.filter(c => c.id !== id) });
        },
        getConnection: (id) => {
          return get().connections.find(c => c.id === id);
        },

        // 活动连接
        activeConnections: [],
        setActiveConnections: (activeConnections) => set({ activeConnections }),
        addActiveConnection: (connection) => {
          const activeConnections = get().activeConnections;
          set({ activeConnections: [...activeConnections, connection] });
        },
        updateActiveConnection: (id, updates) => {
          const activeConnections = get().activeConnections;
          const index = activeConnections.findIndex(c => c.id === id);
          if (index !== -1) {
            const updatedConnections = [...activeConnections];
            updatedConnections[index] = { ...updatedConnections[index], ...updates };
            set({ activeConnections: updatedConnections });
          }
        },
        removeActiveConnection: (id) => {
          const activeConnections = get().activeConnections;
          set({ activeConnections: activeConnections.filter(c => c.id !== id) });
        },
        getActiveConnection: (id) => {
          return get().activeConnections.find(c => c.id === id);
        },

        // 终端管理
        terminals: [],
        setTerminals: (terminals) => set({ terminals }),
        addTerminal: (terminal) => {
          const terminals = get().terminals;
          set({ terminals: [...terminals, terminal] });
        },
        updateTerminal: (id, updates) => {
          const terminals = get().terminals;
          const index = terminals.findIndex(t => t.id === id);
          if (index !== -1) {
            const updatedTerminals = [...terminals];
            updatedTerminals[index] = { ...updatedTerminals[index], ...updates };
            set({ terminals: updatedTerminals });
          }
        },
        removeTerminal: (id) => {
          const terminals = get().terminals;
          set({ terminals: terminals.filter(t => t.id !== id) });
        },
        getTerminal: (id) => {
          return get().terminals.find(t => t.id === id);
        },
        getTerminalsByConnection: (connectionId) => {
          return get().terminals.filter(t => t.connection_id === connectionId);
        },

        // 隧道管理
        tunnels: [],
        setTunnels: (tunnels) => set({ tunnels }),
        addTunnel: (tunnel) => {
          const tunnels = get().tunnels;
          set({ tunnels: [...tunnels, tunnel] });
        },
        updateTunnel: (id, updates) => {
          const tunnels = get().tunnels;
          const index = tunnels.findIndex(t => t.id === id);
          if (index !== -1) {
            const updatedTunnels = [...tunnels];
            updatedTunnels[index] = { ...updatedTunnels[index], ...updates };
            set({ tunnels: updatedTunnels });
          }
        },
        removeTunnel: (id) => {
          const tunnels = get().tunnels;
          set({ tunnels: tunnels.filter(t => t.id !== id) });
        },
        getTunnel: (id) => {
          return get().tunnels.find(t => t.id === id);
        },
        getTunnelsByConnection: (connectionId) => {
          return get().tunnels.filter(t => t.connection_id === connectionId);
        },

        // UI状态
        selectedConnectionId: null,
        setSelectedConnectionId: (id) => set({ selectedConnectionId: id }),
        selectedTerminalId: null,
        setSelectedTerminalId: (id) => set({ selectedTerminalId: id }),
        sidebarOpen: true,
        setSidebarOpen: (open) => set({ sidebarOpen: open }),
        currentPage: 'connections',
        setCurrentPage: (page) => set({ currentPage: page }),

        // 搜索和过滤
        searchQuery: '',
        setSearchQuery: (query) => set({ searchQuery: query }),
        connectionFilter: 'all' as const,
        setConnectionFilter: (filter) => set({ connectionFilter: filter }),

        // 通知和错误
        notifications: [],
        addNotification: (notification) => {
          const notifications = get().notifications;
          const newNotification = {
            ...notification,
            id: Date.now().toString(),
            timestamp: new Date().toISOString(),
            read: false,
          };
          set({ notifications: [newNotification, ...notifications] });
        },
        markNotificationRead: (id) => {
          const notifications = get().notifications;
          const index = notifications.findIndex(n => n.id === id);
          if (index !== -1) {
            const updatedNotifications = [...notifications];
            updatedNotifications[index] = { ...updatedNotifications[index], read: true };
            set({ notifications: updatedNotifications });
          }
        },
        clearNotifications: () => set({ notifications: [] }),

        // 应用状态
        isLoading: false,
        setIsLoading: (loading) => set({ isLoading: loading }),
        error: null,
        setError: (error) => set({ error }),
      }),
      {
        name: 'rustshell-app-store',
        partialize: (state) => ({
          // 只持久化部分状态
          sidebarOpen: state.sidebarOpen,
          currentPage: state.currentPage,
          searchQuery: state.searchQuery,
          connectionFilter: state.connectionFilter,
        }),
      }
    ),
    {
      name: 'rustshell-app-store',
    }
  )
);